<template>
<div class='new-label-model' v-if='isFinish'>
  <el-form label-width='100px' style='width: 90%' :model='addLabelItem' :rules='rules' ref='labelForm'>
    <el-form-item label='标签名称：' prop='name'>
      <el-input show-word-limit maxlength='16' v-model='addLabelItem.name' clearable></el-input>
    </el-form-item>
    <el-form-item label='标签值：' prop='labelValueList' >
      <div class='scroll'>
        <el-tag :key="index" v-for="(tag, index) in addLabelItem.labelValueList" closable :disable-transitions="false"
                @close="handleClose(index)">{{tag.labelValue}}</el-tag>
      </div>
      <el-input class="input-new-tag" v-if="addLabelItem.inputVisible" v-model.trim="addLabelItem.inputValue"
                ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm" maxlength='16' show-word-limit clearable></el-input>
      <el-button v-else class="button-new-tag" size="small" @click="showInput">新增</el-button>
    </el-form-item>
    <el-form-item label='备注：'>
      <el-input type='textarea' show-word-limit :autosize="{ minRows: 3, maxRows: 6}" v-model='addLabelItem.remark' maxlength='20'></el-input>
    </el-form-item>
  </el-form>
  <div slot='footer' class="dialog-footer">
    <el-button type="primary" @click="saveLabelItem()" size="small">保 存</el-button>
    <el-button @click="cancel" size="small">取 消</el-button>
  </div>
</div>
</template>

<script>
  import {mapState} from 'vuex'
  import util from '@/util'
  import {
    saveGoodsLabels,
    updateGoodsLabels
  } from '@/api'
  export default {
    name: 'newLabel',
    data () {
      return {
        isFinish: false,
        glId: '',
        addLabelItem: {
          name: '',
          labelValueList: [],
          remark: '',
          inputVisible: false,
          inputValue: '',
        },
        rules: {
          name: [{required: true, message: '请输入商品标签名称', trigger: 'blur'},
            {validator: util.checkSpace, trigger: 'blur'}],
          labelValueList: [{required: true, message: '请添加标签值', trigger: 'blur'}]
        }
      }
    },
    props: ['datas', 'isAdd'],
    computed: mapState([
      'sub',
      'power',
      'merchantId'
    ]),
    watch: {
      isAdd(cur, old) {
        if (cur == 0) {
          this.getDatas()
        } else {
          this.isFinish = true
        }
      }
    },
    mounted () {
      if (this.datas != null) {
        this.getDatas()
      } else {
        this.isFinish = true
      }
    },
    methods: {
      //接收datas
      getDatas () {
        if (this.datas != null) {
          this.addLabelItem.name = this.datas.name
          this.glId = this.datas.glId
          this.addLabelItem.remark = this.datas.remark
          this.addLabelItem.labelValueList = this.datas.labelValue
          this.isFinish = true
        }
      },
      // 保存新增标签
      saveLabelItem () {
        this.$refs.labelForm.validate((valid) => {
          if (valid) {
            let arr = this.addLabelItem.labelValueList
            let data = {
               name: this.addLabelItem.name,
               remark: this.addLabelItem.remark,
               shopId: this.merchantId,
               type: '',
               labelValueList: JSON.parse(JSON.stringify(arr))
            }
            for (let i=0;i<arr.length;i++) {
              data.labelValueList[i].labelIndex = (i + 1)
            }
            if (this.datas) {
              data.glid = this.glId
              updateGoodsLabels(data).then(res => {
                if (res.code == 200) {
                  if (res.data) {
                    this.$message.error(res.data)
                    return
                  }
                  this.cancel()
                  this.$message.success('修改成功')
                  this.$emit('getLabelList')
                }
              })
            } else {
              saveGoodsLabels(data).then(res => {
                if (res.code == 200) {
                  if (res.data) {
                    this.$message.error(res.data)
                    return
                  }
                  this.cancel()
                  this.$message.success('保存成功')
                  this.$emit('getLabelList')
                }
              })
            }
          }
        })
      },
      cancel () {
        this.addLabelItem.name = ''
        this.id = ''
        this.addLabelItem.remark = ''
        this.addLabelItem.id = ''
        this.addLabelItem.labelValueList = []
        this.addLabelItem.inputVisible = false
        this.addLabelItem.inputValue = ''
        this.$refs.labelForm.clearValidate()
        this.isFinish = false
        this.$emit('cancelAddLabel');
      },
      showInput () {
        if (this.addLabelItem.labelValueList.length == 100) {
          this.$message.error('最多新增100条标签值哦~')
          return
        }
        this.addLabelItem.inputVisible = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },

      handleInputConfirm () {
        let inputValue = this.addLabelItem.inputValue
        let arr = this.addLabelItem.labelValueList
        if (inputValue) {
          for (let i=0;i<arr.length;i++) {
            if (arr[i].labelValue == inputValue) {
              this.$message.error('该标签值已存在，请重新输入!')
              return
            }
          }
          this.$nextTick(()=>{
            this.addLabelItem.labelValueList.push({
              id: null,
              labelValue:inputValue
            })
            this.$refs.labelForm.validateField("labelValueList");
            this.addLabelItem.inputVisible = false
            this.addLabelItem.inputValue = ''
          })
        } else {
          this.addLabelItem.inputVisible = false
          this.addLabelItem.inputValue = ''
        }
      },
      //新增标签关闭
      handleClose (index) {
        this.addLabelItem.labelValueList.splice(index, 1)
      },
    }
  }
</script>

<style scoped lang='less'>
.new-label-model {
  .dialog-footer {
    text-align: center;
    padding-bottom: 20px;
  }
}
</style>
<style>
  .el-tag {
    margin-right: 10px;
  }

  .button-new-tag {
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 300px;
    vertical-align: bottom;
  }
  .scroll .el-form-item__content {
    max-height: 160px;
    overflow-y: scroll;
    overflow-x: hidden;
  }
</style>
